package com.yinuo.interceptors;

import com.yinuo.common.SystemWaiter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class ImagesInterceptor extends HandlerInterceptorAdapter {

    public ImagesInterceptor() {
        super();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        String suffix = uri.substring(uri.lastIndexOf("/"));
        String[] ss = suffix.split("\\.");
        String imageSuffix = null;
        if(ss.length>1){
            imageSuffix = ss[1];
            if("bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,webp".indexOf(imageSuffix)!=-1){
                if(uri.contains("uploadedFiles")){
                    String imgPath = SystemWaiter.getFilesRootPath()+"/"+uri;
                    InputStream in = new FileInputStream(imgPath);
                    OutputStream out = response.getOutputStream();
                    byte b[] = new byte[2048];
                    while((in.read(b))>0){
                        out.write(b,0,b.length);
                    }
                    in.close();
                    out.close();
                    return false;
                }
            }
        }
        return super.preHandle(request,response,handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }
}